<?php

namespace app\admin\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Loader;
use think\Request;
use think\Queue;
use app\index\controller\Notify;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }

    public function importUserList()
    {
        $input = Request()->param();

        $filePath = $input['filePath'];

        // 对应的列名
        $columns = ['username', 'gender', 'role_name', 'birth_date', 'height', 'weight', 'occupation', 'body_type', 'residence', 'hukou', 'marital_status', 'education_level', 'company_type', 'annual_income', 'housing_status', 'car_status', 'hobby', 'mobile', 'wechat', 'qq', 'requirement_age', 'requirement_height', 'requirement_body_type', 'requirement_marital_status', 'requirement_education_level', 'requirement_annual_income', 'requirement_has_children', 'requirement_buying_status', 'requirement_car_status', 'requirement_residence', 'is_recommend', 'rz_status'];

        // 调用导入方法
        $data = importExcel($filePath, $columns);
        Db::startTrans();
        try {
            $time = time();
            foreach ($data as &$v) {
                $mobile = $v['mobile'];
                if ($mobile) {
                    $count = Db::name('user')->where(['mobile' => $mobile])->count();
                    if ($count > 0) continue;
                }

                $role_name = $v['role_name'];
                $role_id = Db::name('role')->where(['name' => $role_name])->value('id');

                $user_data = [
                    'nickname' => $v['username'],
                    'id_num' => createIdNum(),
                    'mobile' => $mobile,
                    'qq' => $v['qq'],
                    'wechat' => $v['wechat'],
                    'role_id' => $role_id ? : 0,
                    'is_recommend' => $v['is_recommend'] == '是' ? 1 : 0,
                    'update_time' => $time,
                    'create_time' => $time
                ];
                $user_id = Db::name('user')->insertGetId($user_data);

                if ($user_id) {
                    $user_details_data = [
                        'user_id' => $user_id,
                        'username' => $v['username'] ? : '',
                        'gender' => $v['gender'] ? : '',
                        'birth_date' => $v['birth_date'] ? : '',
                        'height' => $v['height'] ? : 0,
                        'weight' => $v['weight'] ? : 0,
                        'occupation' => $v['occupation'] ? : '',
                        'body_type' => $v['body_type'] ? : '',
                        'residence' => $v['residence'] ? : '',
                        'hukou' => $v['hukou'] ? : '',
                        'marital_status' => $v['marital_status'] ? : '',
                        'education_level' => $v['education_level'] ? : '',
                        'company_type' => $v['company_type'] ? : '',
                        'annual_income' => $v['annual_income'] ? : '',
                        'housing_status' => $v['housing_status'] ? : '',
                        'car_status' => $v['car_status'] ? : '',
                        'hobby' => $v['hobby'] ? doHobby($v['hobby']) : '',
                        'requirement_age' => $v['requirement_age'] ? convertRange($v['requirement_age'], '岁') : '',
                        'requirement_height' => $v['requirement_height'] ? convertRange($v['requirement_height'], 'cm') : '',
                        'requirement_body_type' => $v['requirement_body_type'] ? : '',
                        'requirement_marital_status' => $v['requirement_marital_status'] ? : '',
                        'requirement_education_level' => $v['requirement_education_level'] ? : '',
                        'requirement_annual_income' => $v['requirement_annual_income'] ? : '',
                        'requirement_has_children' => $v['requirement_has_children'] ? : '',
                        'requirement_buying_status' => $v['requirement_buying_status'] ? : '',
                        'requirement_car_status' => $v['requirement_car_status'] ? : '',
                        'requirement_residence' => $v['requirement_residence'] ? : '',
                        'rz_status' => $v['rz_status'] == '是' ? 1 : 0,
                    ];
                    Db::name('user_details')->insert($user_details_data);
                } else {
                    continue;
                }
            }

            Db::commit();
            adminReturn(1, '导入成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, 'excel文件异常');
        }

    }

    /**
     * 用户列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $username = $input['username'] ? : '';
        $mobile = $input['mobile'] ? : '';
        $id_num = $input['id_num'] ? : '';
        $gender = $input['gender'] ? : '';
        $rz_status = $input['rz_status'] ? : 0;
        $marital_status = $input['marital_status'] ? : '';
        $education_level = $input['education_level'] ? : '';
        $annual_income = $input['annual_income'] ? : '';
        $housing_status = $input['housing_status'] ? : '';
        $car_status = $input['car_status'] ? : '';
        $age = $input['age'] ? : '';
        $create_time = $input['create_time'] ? : '';
        $province = $input['province'] ? : '';
        $city = $input['city'] ? : '';
        $area = $input['area'] ? : '';

        $where['u.status'] = 1;
        $where['u.is_admin'] = 0;

        if ($username) $where['u.nickname|d.username'] = ['LIKE', "%{$username}%"];
        if ($id_num) $where['u.id_num'] = ['LIKE', "%{$id_num}%"];
        if ($mobile) $where['u.mobile'] = ['LIKE', "%{$mobile}%"];
        if ($gender) $where['d.gender'] = $gender;
        if ($rz_status) $where['d.rz_status'] = $rz_status == 1 ? 1 : 0;
        if ($marital_status) $where['d.marital_status'] = $marital_status;
        if ($education_level) $where['d.education_level'] = $education_level;
        if ($annual_income) $where['d.annual_income'] = $annual_income;
        if ($housing_status) $where['d.housing_status'] = $housing_status;
        if ($car_status) $where['d.car_status'] = $car_status;
        if ($age) $where['d.age'] = $age;
        if ($create_time) $where['d.create_time'] = ['BETWEEN', [strtotime($create_time), strtotime($create_time . ' 23:59:59')]];
        if ($area) {
            $where['d.residence'] = ['LIKE', "%${province}-${city}-${area}%"];
        } elseif ($city) {
            $where['d.residence'] = ['LIKE', "%${province}-${city}%"];
        } elseif ($province) {
            $where['d.residence'] = ['LIKE', "%${province}%"];
        }

        $list = Db::name('user u')->join('blind_user_details d', 'u.id = d.user_id', 'left')
            ->field('u.id user_id,u.nickname,u.id_num,u.mobile,u.is_recommend,d.*')
            ->where($where)
            ->order('u.openid desc,u.sort asc,u.is_recommend asc,u.id desc')
            ->paginate()->each(function ($val) {
                // 查看该用户已开通的最高等级会员
                $user_service_info = Db::name('user_service')->where(['user_id' => $val['id'], 'expire_time' => ['gt', time()]])->order('price desc, id desc')->find();
                if ($service_id = $user_service_info['service_id']) {
                    $level_num = Db::name('service')->where('id', $service_id)->value('level_num');
                }
                $val['level_num'] = $level_num ? : 0;

                return $val;
            });

        $this->assign('list', $list);
        $this->assign('title', '用户列表');

        // 用户排序
        $sort_list = Db::name('user u')->join('blind_user_details d', 'u.id = d.user_id')
            ->field('u.id,u.nickname,u.mobile,d.username')
            ->order('u.sort asc,u.is_recommend asc,id desc')
            ->select();
        $this->assign('sort_list', $sort_list);

        $search_count = Db::name('user u')->join('blind_user_details d', 'u.id = d.user_id')
            ->where($where)
            ->count();
        $this->assign('search_count', $search_count);

        // 省市区三级联动数据
        $region_list_json = file_get_contents(RUNTIME_PATH . 'region.json');
        $this->assign('region_list', json_decode($region_list_json, true));
        $this->assign('region_list_json', $region_list_json);

        $maritalStatus = array_values(array_filter(C('MARITAL_STATUS')));
        $this->assign('maritalStatus', $maritalStatus);
        $educationLevel = array_values(array_filter(C('EDUCATION_LEVEL')));
        $this->assign('educationLevel', $educationLevel);
        $annualIncome = array_values(array_filter(C('ANNUAL_INCOME')));
        $this->assign('annualIncome', $annualIncome);
        $housingStatus = array_values(array_filter(C('HOUSING_STATUS')));
        $this->assign('housingStatus', $housingStatus);
        $carStatus = array_values(array_filter(C('CAR_STATUS')));
        $this->assign('carStatus', $carStatus);

        $this->assign('province', $input['province'] ? : '');
        $this->assign('city', $input['city'] ? : '');
        $this->assign('area', $input['area'] ? : '');

        $href_url = $_SERVER['REQUEST_URI'];
        session('href_url', $href_url);

        $service_list = Db::name('service')->where(['status' => 1])->select();
        $this->assign('service_list', $service_list);

        return $this->view->fetch();
    }

    /**
     * 绑定用户
     * */
    public function bindUser()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $is_bind = $input['is_bind'] ? : 0;// 1：绑定操作，0：手机号查找用户
            if ($is_bind == 0) {
                $mobile = $input['mobile'];
                $type = $input['type'] ? : 1; // 1：查找微信用户手机号，2：查找excel用户手机号

                if (empty($mobile)) apiReturn(2, '手机号缺失');

                $where['mobile'] = $mobile;
                if ($type == 1) {
                    $where['openid'] = ['<>', ''];
                } else {
                    $where['openid'] = '';
                }

                $info = Db::name('user')->field('id,nickname')->where($where)->find();
                if ($info) {
                    $username = Db::name('user_details')->where(['user_id' => $info['id']])->value('username');

                    $data = [
                        'id' => $info['id'],
                        'nickname' => $info['nickname'] ? : '',
                        'username' => $username ? : ''
                    ];

                    apiReturn(1, '获取数据成功', $data);
                } else {
                    apiReturn(2, '用户不存在');
                }
            } else {
                $wx_id = $input['wx_id'];
                $excel_id = $input['excel_id'];

                if (empty($wx_id)) apiReturn(2, '请输入微信用户手机号');
                if (empty($excel_id)) apiReturn(2, '请输入资料用户手机号');
                if ($wx_id == $excel_id) apiReturn(2, '用户信息一致，无法进行绑定');

                $wx_user_detail = Db::name('user_details')->where(['user_id' => $wx_id])->find();
                $excel_user_detail = Db::name('user_details')->where(['user_id' => $excel_id])->find();

                if (empty($wx_user_detail)) apiReturn(2, '微信用户不存在');
                if (empty($excel_user_detail)) apiReturn(2, '资料用户不存在');

                // 将excel资料用户的数据同步到微信用户数据中，微信用户的优先级高于excel资料用户
                Db::startTrans();
                try {
                    $data = [
                        'username' => $wx_user_detail['username'] ? : $excel_user_detail['username'],
                        'gender' => $wx_user_detail['gender'] ? : $excel_user_detail['gender'],
                        'birth_date' => $wx_user_detail['birth_date'] && $wx_user_detail['birth_date'] != '0000-00-00' ? $wx_user_detail['birth_date'] : $excel_user_detail['birth_date'],
                        'age' => $wx_user_detail['age'] ? : $excel_user_detail['age'],
                        'height' => $wx_user_detail['height'] ? : $excel_user_detail['height'],
                        'weight' => $wx_user_detail['weight'] ? : $excel_user_detail['weight'],
                        'body_type' => $wx_user_detail['body_type'] ? : $excel_user_detail['body_type'],
                        'residence' => $wx_user_detail['residence'] && $wx_user_detail['residence'] != '-' ? $excel_user_detail['residence'] : $excel_user_detail['residence'],
                        'hukou' => $wx_user_detail['hukou'] && $wx_user_detail['hukou'] != '-' ? $wx_user_detail['hukou'] : $excel_user_detail['hukou'],
                        'marital_status' => $wx_user_detail['marital_status'] ? : $excel_user_detail['marital_status'],
                        'education_level' => $wx_user_detail['education_level'] ? : $excel_user_detail['education_level'],
                        'occupation' => $wx_user_detail['occupation'] ? : $excel_user_detail['occupation'],
                        'company_type' => $wx_user_detail['company_type'] ? : $excel_user_detail['company_type'],
                        'annual_income' => $wx_user_detail['annual_income'] ? : $excel_user_detail['annual_income'],
                        'housing_status' => $wx_user_detail['housing_status'] ? : $excel_user_detail['housing_status'],
                        'car_status' => $wx_user_detail['car_status'] ? : $excel_user_detail['car_status'],
                        'smoking' => $wx_user_detail['smoking'] ? : $excel_user_detail['smoking'],
                        'drinking' => $wx_user_detail['drinking'] ? : $excel_user_detail['drinking'],
                        'ethnicity' => $wx_user_detail['ethnicity'] ? : $excel_user_detail['ethnicity'],
                        'has_children' => $wx_user_detail['has_children'] ? : $excel_user_detail['has_children'],
                        'family_background' => $wx_user_detail['family_background'] ? : $excel_user_detail['family_background'],
                        'family_rank' => $wx_user_detail['family_rank'] ? : $excel_user_detail['family_rank'],
                        'accepts_long_distance' => $wx_user_detail['accepts_long_distance'] ? : $excel_user_detail['accepts_long_distance'],
                        'marriage_time' => $wx_user_detail['marriage_time'] ? : $excel_user_detail['marriage_time'],
                        'wants_children' => $wx_user_detail['wants_children'] ? : $excel_user_detail['wants_children'],
                        'willing_to_live_with_parents' => $wx_user_detail['willing_to_live_with_parents'] ? : $excel_user_detail['willing_to_live_with_parents'],
                        'alma_mater' => $wx_user_detail['alma_mater'] ? : $excel_user_detail['alma_mater'],
                        'photos' => $wx_user_detail['photos'] ? : $excel_user_detail['photos'],
                        'hobby' => $wx_user_detail['hobby'] ? : $excel_user_detail['hobby'],
                        'rz_status' => $wx_user_detail['rz_status'] ? : $excel_user_detail['rz_status'],
                        'requirement_age' => $wx_user_detail['requirement_age'] ? : $excel_user_detail['requirement_age'],
                        'requirement_height' => $wx_user_detail['requirement_height'] ? : $excel_user_detail['requirement_height'],
                        'requirement_body_type' => $wx_user_detail['requirement_body_type'] ? : $excel_user_detail['requirement_body_type'],
                        'requirement_marital_status' => $wx_user_detail['requirement_marital_status'] ? : $excel_user_detail['requirement_marital_status'],
                        'requirement_education_level' => $wx_user_detail['requirement_education_level'] ? : $excel_user_detail['requirement_education_level'],
                        'requirement_annual_income' => $wx_user_detail['requirement_annual_income'] ? : $excel_user_detail['requirement_annual_income'],
                        'requirement_residence' => $wx_user_detail['requirement_residence'] != '-' ? $wx_user_detail['requirement_residence'] : $excel_user_detail['requirement_residence'],
                        'requirement_has_children' => $wx_user_detail['requirement_has_children'] ? : $excel_user_detail['requirement_has_children'],
                        'requirement_buying_status' => $wx_user_detail['requirement_buying_status'] ? : $excel_user_detail['requirement_buying_status'],
                        'requirement_car_status' => $wx_user_detail['requirement_car_status'] ? : $excel_user_detail['requirement_car_status']
                    ];
                    Db::name('user_details')->where(['user_id' => $wx_id])->update($data);

                    Db::commit();
                    apiReturn(1, '绑定成功');
                } catch (\Exception $e) {
                    Db::rollback();
                    apiReturn(2, '绑定失败', $e->getMessage());
                }
            }
        } else {
            $this->assign('title', '绑定用户');
            return $this->view->fetch();
        }
    }

    /**
     * 服务授权
     * */
    public function payService()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $user_id = $input['user_id'];
            $service_id = $input['service_id'];

            if (empty($user_id)) apiReturn(2, '请输入正确的微信用户手机号');
            if (empty($service_id)) apiReturn(2, '请选择服务');
            $user_info = Db::name('user')->field('id,openid')->where(['id' => $user_id])->find();
            if (empty($user_info) || !$user_info['openid']) apiReturn(2, '用户信息有误');
            $service_info = Db::name('service')->where(['id' => $service_id])->find();
            if (empty($service_info) || !$service_info['name'] || !$service_info['price']) apiReturn(2, '服务信息有误');

            // 查看该用户已开通的最高等级会员
            $user_service_info = Db::name('user_service')->where(['user_id' => $user_id, 'expire_time' => ['gt', time()]])->order('price desc')->find();
            if ($service_info['price'] < $user_service_info['price'] && $service_info['use_day'] > 0) apiReturn(2, '该用户已开通更高等级会员，无需再次开通');

            $time = time();
            if ($service_info) {
                // 查询是否有可用优惠券信息

                // 生成待支付订单
                $order_sn = 'SN' . date('YmdHis', $time) . mt_rand(1000, 9999);
                $pay_price = $service_info['price'];

                $data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'service_id' => $service_info['id'],
                    'service_name' => $service_info['name'],
                    'service_price' => $service_info['price'],
                    'service_rate' => $service_info['rate'],
                    'service_use_day' => $service_info['use_day'],
                    'service_look_count' => $service_info['look_count'],
                    'coupon_name' => '',
                    'coupon_price' => 0,
                    'pay_price' => $pay_price,
                    'from' => 2,
                    'create_time' => $time
                ];
                Db::name('order')->insert($data);

                $Notify = new Notify();
                $Notify->doAdminServiceOrder($order_sn);

                apiReturn(1, '服务授权成功');
            } else {
                apiReturn(2, '服务授权失败');
            }
        } else {
            $service_list = Db::name('service')->where(['status' => 1])->select();
            $this->assign('service_list', $service_list);

            $this->assign('title', '服务授权');
            return $this->view->fetch();
        }
    }

    /**
     * 菜单排序
     * */
    public function saveUserSort()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('user')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 编辑用户
     * */
    public function doUser()
    {
        if (Request()->isPost()) {

            $input = Request()->param();

            $id = $input['id'];
            $username = $input['username'];
            $avatar = $input['avatar'];
            $gender = $input['gender'];
            $birth_date = $input['birth_date'];
            $height = $input['height'];
            $weight = $input['weight'];
            $body_type = $input['body_type'];
            $is_recommend = $input['is_recommend'];
            $role_id = $input['role_id'];
            $residence = $input['residence'];
            $hukou = $input['hukou'];
            $marital_status = $input['marital_status'];
            $education_level = $input['education_level'];
            $occupation = $input['occupation'];
            $company_type = $input['company_type'];
            $annual_income = $input['annual_income'];
            $housing_status = $input['housing_status'];
            $car_status = $input['car_status'];
            $hobby = $input['hobby'];
            $msg_tags = $input['msg_tags'];
            /*$smoking = $input['smoking'];//是否吸烟
            $drinking = $input['drinking'];//是否喝酒
            $ethnicity = $input['ethnicity'];//民族
            $has_children = $input['has_children'];//是否有孩子
            $family_background = $input['family_background'];//家庭背景
            $family_rank = $input['family_rank'];//家庭排行
            $accepts_long_distance = $input['accepts_long_distance'];//是否接受异地恋
            $marriage_time = $input['marriage_time'];//何时结婚
            $wants_children = $input['wants_children'];//是否想要孩子
            $willing_to_live_with_parents = $input['willing_to_live_with_parents'];//愿意与对方父母同住*/
            $mobile = $input['mobile'];
            $qq = $input['qq'];
            $wechat = $input['wechat'];
            /*$alma_mater = $input['alma_mater'];//毕业院校*/
            $photos = $input['photos'];
            $rz_status = $input['rz_status'];
            $requirement_age = $input['requirement_age'];
            $requirement_height = $input['requirement_height'];
            $requirement_body_type = $input['requirement_body_type'];
            $requirement_marital_status = $input['requirement_marital_status'];
            $requirement_education_level = $input['requirement_education_level'];
            $requirement_annual_income = $input['requirement_annual_income'];
            $requirement_residence = $input['requirement_residence'];
            $requirement_has_children = $input['requirement_has_children'];
            $requirement_buying_status = $input['requirement_buying_status'];
            $requirement_car_status = $input['requirement_car_status'];

            $age_len = count(array_filter($requirement_age));
            if ($age_len == 0) {
                $requirement_age = '';
            } else if ($age_len == 1) {
                $requirement_age = implode(' - ', $requirement_age);
            } else {
                $requirement_age = implode(' - ', sortArr($requirement_age));
            }

            $height_len = count(array_filter($requirement_height));
            if ($height_len == 0) {
                $requirement_height = '';
            } else if ($height_len == 1) {
                $requirement_height = implode(' - ', $requirement_height);
            } else {
                $requirement_height = implode(' - ', sortArr($requirement_height));
            }

            if (empty($username)) adminReturn(2, '请输入姓名');

            if ($mobile) {
                $count_where['mobile'] = $mobile;
                if ($id) $count_where['id'] = ['neq', $id];
                $mobile_count = Db::name('user')->where($count_where)->count();
                if ($mobile_count > 0) adminReturn(2, '手机号已存在');
            }

            /*if ($role_id == 1) {
                // 普通用户才需要完善这些信息
                if (empty($avatar)) adminReturn(2, '请上传头像');
                if (empty($gender)) adminReturn(2, '请选择性别');
                if (empty($birth_date)) adminReturn(2, '请选择出生日期');
                $age = calculateAge($birth_date);
                if (empty($height)) adminReturn(2, '请选择身高');
                if (empty($weight)) adminReturn(2, '请选择体重');
                if (empty($body_type)) adminReturn(2, '请选择体型');
                if (empty($residence)) adminReturn(2, '请选择居住地');
                if (empty($hukou)) adminReturn(2, '请选择户籍地');
                if (empty($marital_status)) adminReturn(2, '请选择婚况');
                if (empty($education_level)) adminReturn(2, '请选择学历');
                if (empty($occupation)) adminReturn(2, '请选择职业');
                if (empty($company_type)) adminReturn(2, '请选择公司性质');
                if (empty($annual_income)) adminReturn(2, '请选择年收入');
                if (empty($housing_status)) adminReturn(2, '请选择住房情况');
                if (empty($car_status)) adminReturn(2, '请选择车辆情况');
            }*/

            $user_details_info = Db::name('user_details')->where(['user_id' => $id])->find();
            if (empty($user_details_info)) apiReturn(2, '用户信息不存在');

            Db::startTrans();
            try {
                $time = time();
                if ($id) {
                    // 编辑
                    $user_data = [
                        'avatar' => $avatar,
                        'mobile' => $mobile,
                        'wechat' => $wechat,
                        'qq' => $qq,
                        'is_recommend' => $is_recommend,
                        'role_id' => $role_id,
                        'is_set' => 1,
                        'msg_tags' => $msg_tags ? json_encode($msg_tags, JSON_UNESCAPED_UNICODE) : '',
                        'update_time' => $time
                    ];
                    Db::name('user')->where(['id' => $id])->update($user_data);

                    $details_data = [
                        'username' => $username,
                        'gender' => $gender,
                        'birth_date' => $birth_date,
                        'age' => calculateAge($birth_date),
                        'height' => $height,
                        'weight' => $weight,
                        'occupation' => $occupation,
                        'body_type' => $body_type,
                        'residence' => implode(' - ', $residence),
                        'hukou' => implode(' - ', $hukou),
                        'marital_status' => $marital_status,
                        'education_level' => $education_level,
                        'company_type' => $company_type,
                        'annual_income' => $annual_income,
                        'housing_status' => $housing_status,
                        'car_status' => $car_status,
                        'hobby' => $hobby ? json_encode($hobby, JSON_UNESCAPED_UNICODE) : '',
                        'requirement_age' => $requirement_age,
                        'requirement_height' => $requirement_height,
                        'requirement_body_type' => $requirement_body_type,
                        'requirement_marital_status' => $requirement_marital_status,
                        'requirement_education_level' => $requirement_education_level,
                        'requirement_annual_income' => $requirement_annual_income,
                        'requirement_residence' => implode(' - ', $requirement_residence),
                        'requirement_has_children' => $requirement_has_children,
                        'requirement_buying_status' => $requirement_buying_status,
                        'requirement_car_status' => $requirement_car_status,
                        'photos' => $photos,
                        'rz_status' => $rz_status,
                        'update_time' => $time
                    ];

                    if ($user_details_info['rz_status'] == 0 && $rz_status == 1) {
                        // 认证审核通过
                        $msg_data = [
                            'user_id' => $id,
                            'title' => '认证审核',
                            'content' => '恭喜，您的信息已经通过平台认证，正式成为平台会员。',
                            'type' => 1,
                            'create_time' => $time
                        ];
                        Db::name('msg')->insert($msg_data);
                    }

                    Db::name('user_details')->where(['user_id' => $id])->update($details_data);

                    Db::commit();
                    adminReturn(1, '提交成功', session('href_url') ? : url('userList'));
                } else {
                    // 新增
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '提交失败' . $e->getMessage());
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('user u')->join('blind_user_details d', 'u.id = d.user_id', 'left')->where(['u.id' => $id])->find();

                $info['msg_tags'] = json_decode($info['msg_tags'], true);

                $info['photos_arr'] = doImgs($info['photos']);
                // 年龄要求
                $info['requirement_age'] = explode(' - ', $info['requirement_age']);
                // 身高要求
                $info['requirement_height'] = explode(' - ', $info['requirement_height']);

                // 居住地
                $residence_arr = explode('-', str_replace(' ', '', $info['residence']));
                // 户籍地
                $hukou_arr = explode('-', str_replace(' ', '', $info['hukou']));
                // 要求居住地
                $requirement_residence_arr = explode('-', str_replace(' ', '', $info['requirement_residence']));
            } else {
                $residence_arr = [];
            }

            $hobby_arr = array_values(array_filter(C('HOBBY')));
            $this->assign('hobby_arr', $hobby_arr);

            $msg_tags = array_values(array_filter(C('MSG_TAGS')));
            $this->assign('msg_tags', $msg_tags);

            $info['hobby'] = json_decode($info['hobby'], true);

            $this->assign('residence_arr', json_encode($residence_arr, JSON_UNESCAPED_UNICODE));
            $this->assign('hukou_arr', json_encode($hukou_arr, JSON_UNESCAPED_UNICODE));
            $this->assign('requirement_residence_arr', json_encode($requirement_residence_arr, JSON_UNESCAPED_UNICODE));
            $this->assign('info', $info);
            $this->assign('title', '编辑用户');

            // 省市区三级联动数据
            $region_list_json = file_get_contents(RUNTIME_PATH . 'region.json');
            $this->assign('region_list', json_decode($region_list_json, true));
            $this->assign('region_list_json', $region_list_json);

            $role_list = Db::name('role')->order('id asc')->select();
            $this->assign('role_list', $role_list);

            return $this->view->fetch();
        }
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'] ? : '';
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $coupon_name = $input['coupon_name'];
        $is_pay = $input['is_pay'];

        $where["a.id"] = ["gt", 0];
        if ($mobile) $where['b.mobile'] = ['LIKE', "%{$mobile}%"];
        if (!empty($start_time) && empty($end_time)) {
            $where["a.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["a.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        if ($coupon_name) $where['a.coupon_name'] = $coupon_name;
        if ($is_pay == 1) {
            $where['a.pay_time'] = ['gt', 0];
        } else if ($is_pay == 2) {
            $where['a.pay_time'] = ['eq', 0];
        }

        $list = Db::name('order a')->field("a.*,b.mobile,b.nickname")->join('user b', "a.user_id = b.id", "left")->where($where)->order('create_time desc')->paginate();

        $this->assign('list', $list);

        // 总实付金额
        $all_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->sum('pay_price');
        $this->assign('all_price', sprintf(' % .2f', $all_price));
        // 总实付金额【已支付】
        $all_pay_price = Db::name('order a')->join('user b', "a.user_id = b.id", "left")->where($where)->where(['a.pay_time' => ['gt', 0]])->sum('pay_price');
        $this->assign('all_pay_price', sprintf(' % .2f', $all_pay_price));


        $coupon_list = Db::name('coupon')->where(['status' => 1])->select();
        $this->assign('coupon_list', $coupon_list);

        $this->assign('title', '订单列表');

        return $this->fetch();
    }


    /**
     * 删除订单
     * */
    public function delOrder()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();

        $user_id = $info['user_id'];
        $user_info = Db::name('user')->where('id', $user_id)->find();

        $service_id = $info['service_id'];
        if (!$user_id || !$service_id || empty($user_info)) adminReturn(2, '数据异常，删除失败');

        if ($info) {
            Db::startTrans();
            try {
                // 删除订单
                Db::name('order')->where(['id' => $id])->delete();

                // 删除服务记录
                $res = Db::name('user_service')->where(['user_id' => $user_id, 'service_id' => $service_id, 'create_time' => $info['pay_time']])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '服务记录不存在，删除失败');
                }

                if ($info['is_create_profit'] > 0) {
                    if (!$user_info['up_user_id']) {
                        Db::rollback();
                        adminReturn(2, '上级用户数据异常，删除失败');
                    }

                    $profit_info = Db::name('profit')->where(['user_id' => $user_info['up_user_id'], 'order_id' => $id])->find();
                    if (empty($profit_info)) {
                        Db::rollback();
                        adminReturn(2, '抽佣记录不存在，删除失败');
                    }

                    $up_user_info = Db::name('user')->where('id', $user_info['up_user_id'])->find();
                    if ($up_user_info['profit'] < $profit_info['profit']) {
                        Db::rollback();
                        adminReturn(2, '上级用户收益不足，删除失败');
                    }

                    // 删除收益记录
                    Db::name('profit')->where('id', $profit_info['id'])->delete();

                    // 修改上级收益信息
                    $up_user_data = [
                        'profit' => $up_user_info['profit'] - $profit_info['profit'],
                        'all_profit' => $up_user_info['all_profit'] - $profit_info['profit'],
                        'update_time' => time()
                    ];
                    Db::name('user')->where('id', $user_info['up_user_id'])->update($up_user_data);


                }


                Db::commit();
                adminReturn(1, '删除成功');
            } catch (Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 抽佣明细
     * */
    public function profitList()
    {
        $where['type'] = 1;
        $list = Db::name('profit')->where($where)->order('update_time desc')->paginate()->each(function ($val) {
            $nickname = Db::name('user')->where(['id' => $val['user_id']])->value('nickname');
            $val['nickname'] = $nickname ? : '';

            $order_sn = Db::name('order')->where(['id' => $val['order_id']])->value('order_sn');
            $val['order_sn'] = $order_sn ? : '';

            //0：冻结，1：有效，-1：无效
            switch ($val['status']) {
                case 0:
                    $val['status_desc'] = '冻结';
                    break;
                case 1:
                    $val['status_desc'] = '有效';
                    break;
                case -1:
                    $val['status_desc'] = '无效';
                    break;
            }

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '抽佣明细');
        return $this->view->fetch();
    }

    /**
     * 抽佣用户列表
     * */
    public function profitUserList()
    {
        $where['status'] = 1;
        $where['role_id'] = ['gt', 1];
        $where['is_admin'] = 0;

        $list = Db::name('user')
            ->where($where)
            ->order('sort asc,is_recommend asc,id desc')
            ->paginate()->each(function ($v) {
                $share_count = Db::name('user')->where(['up_user_id' => $v['id']])->count();
                $v['share_count'] = $share_count;
                return $v;
            });

        $this->assign('list', $list);
        $this->assign('title', '抽佣用户列表');

        return $this->view->fetch();
    }

    /**
     * 推广列表
     * */
    public function shareUserList()
    {
        $input = Request()->param();

        $id = $input['id'];

        $where['u.up_user_id'] = $id;

        $list = Db::name('user u')->join('blind_user_details d', 'u.id = d.user_id', 'left')
            ->field('u.id,u.nickname,u.mobile,d.username,u.create_time')
            ->where($where)
            ->order('u.sort asc,u.is_recommend asc,u.id desc')
            ->paginate();

        $this->assign('list', $list);
        $this->assign('title', '推广列表');

        return $this->view->fetch();
    }


    /**
     * 用户抽佣明细
     * */
    public function userProfitList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $where['type'] = 1;

        if ($id) $where['user_id'] = $id;

        $list = Db::name('profit')->where($where)->order('update_time desc')->paginate()->each(function ($val) {
            $nickname = Db::name('user')->where(['id' => $val['user_id']])->value('nickname');
            $val['nickname'] = $nickname ? : '';

            $order_sn = Db::name('order')->where(['id' => $val['order_id']])->value('order_sn');
            $val['order_sn'] = $order_sn ? : '';

            //0：冻结，1：有效，-1：无效
            switch ($val['status']) {
                case 0:
                    $val['status_desc'] = '冻结';
                    break;
                case 1:
                    $val['status_desc'] = '有效';
                    break;
                case -1:
                    $val['status_desc'] = '无效';
                    break;
            }

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '用户抽佣明细');
        return $this->view->fetch();
    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $list = Db::name('service')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '服务列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 服务
     * */
    public function doService()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $level_num = $input['level_num'];
            $img = $input['img'];
            $price = $input['price'];
            $use_day = $input['use_day'];
            $look_count = $input['look_count'];
            $chat_count = $input['chat_count'];
            $rate = $input['rate'] ? : 0;
            $role_id = $input['role_id'];
            $content = $input['content'];
            $status = $input['status'];

            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($price)) adminReturn(2, '请输入价格');
            if (empty($content)) adminReturn(2, '请输入介绍');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('service')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $time = time();
            $data = [
                'name' => $name,
                'level_num' => $level_num,
                'img' => $img,
                'price' => $price,
                'use_day' => $use_day,
                'look_count' => $look_count,
                'chat_count' => $chat_count,
                'rate' => $rate,
                'role_id' => $role_id,
                'content' => $content,
                'status' => $status
            ];

            if ($id > 0) {
                $data['update_time'] = $time;
                $res = Db::name('service')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑服务成功', url('serviceList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = $time;
                $res = Db::name('service')->insert($data);
                if ($res) {
                    adminReturn(1, '新增服务成功', url('serviceList'));
                } else {
                    adminReturn(2, '新增服务失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('service')->where(['id' => $id])->find();

            $role_list = Db::name('role')->order('id asc')->select();
            $this->assign('role_list', $role_list);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '服务');

            return $this->view->fetch();
        }
    }

    /**
     * 删除服务
     * */
    public function delService()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '服务ID缺失');

        $info = Db::name('service')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('service')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 优惠券列表
     * */
    public function couponList()
    {
        $list = Db::name('coupon')->paginate()->each(function ($val) {
            $service_name = Db::name('service')->where(['id' => $val['service_id']])->value('name');
            $val['service_name'] = $service_name ? : '';

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '优惠券列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 优惠券
     * */
    public function doCoupon()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $price = $input['price'];
            $service_id = $input['service_id'];
            $time = $input['time'];
            $status = $input['status'];

            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($price)) adminReturn(2, '请输入价格');
            if (empty($service_id)) adminReturn(2, '请选择服务');
            if (empty($time)) adminReturn(2, '请选择生效时间段');

            $time_arr = explode(' - ', $time);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1]);

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('coupon')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $time = time();
            $data = [
                'name' => $name,
                'price' => $price,
                'service_id' => $service_id,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'status' => $status
            ];

            if ($id > 0) {
                $data['update_time'] = $time;
                $res = Db::name('coupon')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $data['create_time'] = $time;
                $res = Db::name('coupon')->insert($data);
                if ($res) {
                    adminReturn(1, '新增优惠券成功', url('couponList'));
                } else {
                    adminReturn(2, '新增优惠券失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('coupon')->where(['id' => $id])->find();
                $time = date('Y - m - d', $info['start_time']) . ' - ' . date('Y - m - d', $info['end_time']);
                $info['time'] = $time;
            }

            $service_list = Db::name('service')->where(['status' => 1])->select();
            $this->assign('service_list', $service_list);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '优惠券');

            return $this->view->fetch();
        }
    }

    /**
     * 删除优惠券
     * */
    public function delCoupon()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '优惠券ID缺失');

        $info = Db::name('coupon')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('coupon')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 提现列表
     * */
    public function withdrawList()
    {
        $input = Request()->param();

        $mobile = $input['mobile'] ? : '';
        $start_time = $input['start_time'];
        $end_time = $input['end_time'];
        $status = $input['status'];

        $where = [];
        if ($mobile) $where['u.mobile'] = ['LIKE', "%{$mobile}%"];
        if (!empty($start_time) && empty($end_time)) {
            $where["w.create_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["w.create_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["w.create_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }
        if ($status) $where['w.status'] = $status - 1;


        $list = Db::name('withdraw w')->join('blind_user u', 'w.user_id = u.id')
            ->field('w .*, u.mobile')
            ->where($where)
            ->order('w.status asc, w.create_time desc')
            ->paginate()->each(function ($val) {
                $username = Db::name('user_details')->where(['user_id' => $val['user_id']])->value('username');
                $val['username'] = $username ? : '';

                switch ($val['status']) {
                    case 0:
                        $val['status_desc'] = '待审核';
                        break;
                    case 1:
                        $val['status_desc'] = '审核通过';
                        break;
                    case 2:
                        $val['status_desc'] = '审核不通过';
                        break;
                }

                return $val;
            });

        // 提现总金额
        $all_profit = Db::name('withdraw w')->join('blind_user u', 'w.user_id = u.id')->where($where)->sum('w.profit');
        $this->assign('all_profit', sprintf(' % .2f', $all_profit));

        $href_url = $_SERVER['REQUEST_URI'];
        session('href_url', $href_url);

        $this->assign('list', $list);
        $this->assign('title', '提现列表');
        return $this->view->fetch();
    }


    /**
     * 提现详情
     * */
    public function doWithdraw()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $status = $input['status'];
            $reason = $input['reason'];

            if (empty($id)) adminReturn(2, '提现ID缺失');
            if ($status == 0) apiReturn(2, '请选择审核状态');

            $info = Db::name('withdraw')->where(['id' => $id])->find();
            if (empty($info)) adminReturn(2, '数据不存在或已删除');

            if ($info['status'] != 0) adminReturn(2, '该提现记录已审核');

            Db::startTrans();
            try {
                $time = time();
                $data = [
                    'status' => $status,
                    'update_time' => $time
                ];

                if ($status == 2) {
                    // 审核不通过
                    $data['reason'] = $reason;

                    // 收益记录处理
                    $profit_data = [
                        'user_id' => $info['user_id'],
                        'withdraw_id' => $id,
                        'profit' => abs($info['profit']),
                        'desc' => '提现申请审核不通过返还收益，原因：' . $reason,
                        'type' => 2,
                        'status' => 1,
                        'update_time' => $time,
                        'create_time' => $time
                    ];
                    Db::name('profit')->insert($profit_data);
                    Db::name('profit')->where(['withdraw_id' => $id])->setField('desc', '提现申请审核不通过，收益已返还');

                    Db::name('user')->where(['id' => $info['user_id']])->setInc('profit', $info['profit']);
                } else {
                    // 审核通过
                    Db::name('profit')->where(['withdraw_id' => $id])->setField('desc', '提现申请审核已通过');
                }

                Db::name('withdraw')->where(['id' => $id])->update($data);

                Db::commit();
                adminReturn(1, '操作成功', session('href_url') ? : url('withdrawList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) {
                $info = Db::name('withdraw')->where(['id' => $id])->find();
                $username = Db::name('user_details')->where(['user_id' => $info['user_id']])->value('username');
                $info['username'] = $username ? : '';

                switch ($info['status']) {
                    case 0:
                        $info['status_desc'] = '待审核';
                        break;
                    case 1:
                        $info['status_desc'] = '审核通过';
                        break;
                    case 2:
                        $info['status_desc'] = '审核不通过';
                        break;
                }
            }

            $this->assign('info', $info);
            $this->assign('title', '提现详情');

            return $this->view->fetch();
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->paginate()->each(function ($val) {
            $type = $val['type'];
            if ($type == 1) {
                $title = Db::name('article')->where(['id' => $val['to_id']])->value('title');
            } else {
                $title = Db::name('service')->where(['id' => $val['to_id']])->value('name');
            }
            $val['title'] = $title ? : '';
            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $type = $input['type'];
            $article_id = $input["article_id"];
            $service_id = $input["service_id"];

            if (empty($img)) adminReturn(2, '请上传banner图');
            if (empty($article_id) && empty($service_id)) adminReturn(2, '请选择链接对象');

            $data = [
                "img" => $img,
                "type" => $type,
                "to_id" => $type == 1 ? $article_id : $service_id,
            ];

            $time = time();
            if ($id > 0) {
                $data['update_time'] = $time;
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $data['create_time'] = $time;
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $article_list = Db::name('article')->field('id,title')->select();
            $this->assign('article_list', $article_list);

            $service_list = Db::name('service')->field('id,name')->select();
            $this->assign('service_list', $service_list);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章分类列表
     * */
    public function articleTypeList()
    {
        $list = Db::name('article_type')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '文章分类列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章分类
     * */
    public function doArticleType()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];

            if (empty($name)) adminReturn(2, '请输入名称');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('article_type')->where($where)->count();
            if ($count > 0) adminReturn(2, '该分类已存在');

            $data = [
                'name' => $name
            ];

            if ($id > 0) {
                $res = Db::name('article_type')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '编辑失败或未编辑');
                }
            } else {
                $res = Db::name('article_type')->insert($data);
                if ($res) {
                    adminReturn(1, '新增文章分类成功', url('articleTypeList'));
                } else {
                    adminReturn(2, '新增文章分类失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('article_type')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '文章分类');

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章分类
     * */
    public function delArticleType()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '分类ID缺失');

        $info = Db::name('article_type')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article_type')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $role_id = $input['role_id'];

        if ($role_id) $where['role_id'] = ['IN', [0, $role_id]];

        $list = Db::name('article')->where($where)->order('id desc')->paginate();

        $role_list = Db::name('role')->select();
        $this->assign('role_list', $role_list);

        $this->assign('list', $list);
        $this->assign('title', '文章列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $content = $input['content'];
            $role_id = $input['role_id'];

            if (empty($title)) adminReturn(2, '请输入标题');
            if (empty($content)) adminReturn(2, '请输入内容');

            $time = time();
            $data = [
                'title' => $title,
                'content' => $content,
                'role_id' => $role_id,
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $role_list = Db::name('role')->order('id asc')->select();
            $this->assign('role_list', $role_list);

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 角色列表
     * */
    public function roleList()
    {
        $list = Db::name('role')->order('id asc')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '角色列表');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 角色
     * */
    public function doRole()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $content = $input['content'];

            if (empty($name)) adminReturn(2, '请输入角色名称');
            if (empty($content)) adminReturn(2, '请输入权益描述');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];

            $count = Db::name('role')->where($where)->count();
            if ($count) adminReturn(2, '角色名称已存在');

            $time = time();
            $data = [
                'name' => $name,
                'content' => $content,
            ];

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('role')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('roleList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('role')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('roleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('role')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '角色');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 删除角色
     * */
    public function delRole()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '角色ID缺失');

        $info = Db::name('role')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('role')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 规则设置
     * */
    public function setRule()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $list = $input['list'];

            if (empty($list)) adminReturn(2, '请完善规则数据');

            $time = time();
            Db::startTrans();
            try {
                if ($list) {
                    foreach ($list as &$val) {
                        $rules = $val['rules'];
                        if ($rules) {
                            $prev_money = 0;
                            $prev_rate = 0;
                            foreach ($rules as &$v) {
                                $money = $v['money'];
                                $rate = $v['rate'];
                                if ($rate <= 0) {
                                    adminReturn(2, '请完善' . $val['name'] . '规则数据');
                                    break;
                                }
                                /*if ($money <= $prev_money || $rate <= $prev_rate) {
                                    adminReturn(2, $val['name'].'规则数据设置有误，排序靠后的达成业绩和提成百分比必须大于排序靠前数据');
                                    break;
                                }*/
                                $prev_money = $money;
                                $prev_rate = $rate;
                            }
                        }

                        $data = [
                            'rules' => json_encode($rules, JSON_UNESCAPED_UNICODE),
                            'update_time' => $time
                        ];
                        Db::name('role')->where(['id' => $val['id']])->update($data);
                    }
                    Db::commit();
                    adminReturn(1, '保存成功');
                } else {
                    Db::rollback();
                    adminReturn(2, '保存失败');
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '保存失败');
            }
        } else {
            $list = Db::name('role')->field('id,name,rules')->where(['id' => ['neq', 1]])->order('id asc')->select();
            if ($list) {
                foreach ($list as &$v) {
                    $v['rules'] = $v['rules'] ? json_decode($v['rules'], true) : [];
                }
            }
            $this->assign('list', $list);
            $this->assign('list_json', json_encode($list, JSON_UNESCAPED_UNICODE));


            $this->assign('title', '规则设置');

            return $this->view->fetch();
        }
    }

    /**
     * 底部菜单列表
     * */
    public function tabbarList()
    {
        $list = Db::name('tabbar')->order('sort asc')->paginate();
        $this->assign('list', $list);
        $this->assign('list_json', json_encode($list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '底部菜单列表');

        return $this->view->fetch();
    }

    /**
     * 编辑底部菜单
     * */
    public function doTabbar()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $img = $input['img'];
            $active_img = $input['active_img'];

            if (empty($name)) adminReturn(2, '请输入菜单名称');
            if (empty($img)) adminReturn(2, '请上传默认图标');
            if (empty($active_img)) adminReturn(2, '请上传选中图标');

            $info = Db::name('tabbar')->where(['id' => $id])->find();
            if (empty($info)) adminReturn(2, '菜单不存在');

            $count = Db::name('tabbar')->where(['id' => ['neq', $id], 'name' => $name])->count();
            if ($count) adminReturn(2, '菜单名称已存在');

            $data = [
                'name' => $name,
                'img' => $img,
                'active_img' => $active_img
            ];

            $res = Db::name('tabbar')->where(['id' => $id])->update($data);
            if ($res) {
                adminReturn(1, '编辑成功', url('tabbarList'));
            } else {
                adminReturn(2, '编辑失败或未编辑');
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('tabbar')->where(['id' => $id])->find();
            $this->assign('info', $info);

            $this->assign('title', '编辑底部菜单');

            return $this->view->fetch();
        }
    }

    /**
     * 相册、联系方式无权限查看提示
     * */
    public function infoAuthArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            $data = [
                'content' => $content,
                'update_time' => time()
            ];

            $res = Db::name('auth_article')->where(['type' => 1])->update($data);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $content = Db::name('auth_article')->where(['type' => 1])->value('content');
            $this->assign('content', $content);

            $this->assign('title', '相册、联系方式无权限查看提示');
            return $this->view->fetch();
        }
    }

    /**
     * 购买服务成功提示
     * */
    public function buyAuthArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $content = $input['content'];

            $data = [
                'content' => $content,
                'update_time' => time()
            ];

            $res = Db::name('auth_article')->where(['type' => 2])->update($data);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $content = Db::name('auth_article')->where(['type' => 2])->value('content');
            $this->assign('content', $content);

            $this->assign('title', '购买服务成功提示');
            return $this->view->fetch();
        }
    }


    /**
     * 会员统计
     * */
    public function userCensus()
    {
        $time_list = Db::name('user')->field("from_unixtime(create_time, '%Y-%m-%d') time")->distinct(true)->where(['id' => ['gt', 1]])->order('create_time asc')->select();
        $user_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $where["create_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];

                $user_count = Db::name('user')->where(['id' => ['gt', 1]])->where($where)->count();
                $user_list[] = $user_count;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('user_list', json_encode($user_list));

        $this->assign('title', '用户统计');

        return $this->fetch();
    }

    /**
     * 交易统计
     * */
    public function orderCensus()
    {
        $input = Request()->param();

        $start_time = $input['start_time'];
        $end_time = $input['end_time'];

        if (!empty($start_time) && empty($end_time)) {
            $where["pay_time"] = ["egt", strtotime($start_time)];
        } elseif (empty($start_time) && !empty($end_time)) {
            $where["pay_time"] = ["elt", strtotime($end_time) + 60 * 60 * 24 - 1];
        } elseif (!empty($start_time) && !empty($end_time)) {
            $where["pay_time"] = ['between', [strtotime($start_time), strtotime($end_time) + 60 * 60 * 24 - 1]];
        }

        $all_pay_price = Db::name('order')->where($where)->where(['pay_time' => ['gt', 0]])->sum('pay_price');
        $this->assign('all_pay_price', sprintf(' % .2f', $all_pay_price));

        $time_list = Db::name('order')->field("from_unixtime(pay_time, '%Y-%m-%d') time")->distinct(true)->where($where)->where(['pay_time' => ['gt', 0]])->order('pay_time asc')->select();

        $order_list = [];
        if ($time_list) {
            foreach ($time_list as $v) {
                $order_where["pay_time"] = ['between', [strtotime($v['time']), strtotime($v['time']) + 60 * 60 * 24 - 1]];
                unset($where['pay_time']);

                $order_pay_price = Db::name('order')->where(['pay_time' => ['gt', 0]])->where($order_where)->sum('pay_price');
                $order_list[] = $order_pay_price;
            }
        }

        $this->assign('time_list', json_encode(array_column($time_list, 'time')));
        $this->assign('order_list', json_encode($order_list));

        $this->assign('title', '交易统计');

        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", ' % ' . $title . ' % '];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $tag = $input['tag'];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'tag' => $tag == '0' ? '' : $tag,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    'tag' => $tag == '0' ? '' : $tag,
                    "content" => $content,
                    "type" => 3,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $msg_tags = array_values(array_filter(C('MSG_TAGS')));
            $this->assign('msg_tags', $msg_tags);

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

}
